<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots" content="noodp" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
        <title>Mqtt入门 - 记录从零开始的过程</title><meta name="Description" content="记录从零开始的过程"><meta property="og:title" content="Mqtt入门" />
<meta property="og:description" content="SpringBoot整合MQTT" />
<meta property="og:type" content="article" />
<meta property="og:url" content="http://example.org/mqtt%E5%85%A5%E9%97%A8/" /><meta property="og:image" content="http://example.org/logo.png"/><meta property="article:section" content="posts" />
<meta property="article:published_time" content="2021-11-17T15:18:13+08:00" />
<meta property="article:modified_time" content="2021-11-17T15:18:13+08:00" />

<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content="http://example.org/logo.png"/>

<meta name="twitter:title" content="Mqtt入门"/>
<meta name="twitter:description" content="SpringBoot整合MQTT"/>
<meta name="application-name" content="LoveIt">
<meta name="apple-mobile-web-app-title" content="LoveIt"><meta name="theme-color" content="#ffffff"><meta name="msapplication-TileColor" content="#da532c"><link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
        <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
        <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"><link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5"><link rel="manifest" href="/site.webmanifest"><link rel="canonical" href="http://example.org/mqtt%E5%85%A5%E9%97%A8/" /><link rel="prev" href="http://example.org/docker%E5%AE%89%E8%A3%85emqx/" /><link rel="next" href="http://example.org/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E4%BB%8B%E7%BB%8D/" /><link rel="stylesheet" href="/lib/normalize/normalize.min.css"><link rel="stylesheet" href="/css/style.min.css"><link rel="stylesheet" href="/lib/fontawesome-free/all.min.css"><link rel="stylesheet" href="/lib/animate/animate.min.css"><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "Mqtt入门",
        "inLanguage": "zh-CN",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "http:\/\/example.org\/mqtt%E5%85%A5%E9%97%A8\/"
        },"genre": "posts","keywords": "mqtt, SpringBoot","wordcount":  1296 ,
        "url": "http:\/\/example.org\/mqtt%E5%85%A5%E9%97%A8\/","datePublished": "2021-11-17T15:18:13+08:00","dateModified": "2021-11-17T15:18:13+08:00","publisher": {
            "@type": "Organization",
            "name": ""},"author": {
                "@type": "Person",
                "name": "Cuasloi"
            },"description": ""
    }
    </script></head>
    <body header-desktop="fixed" header-mobile="auto"><script type="text/javascript">(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('auto' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : 'auto' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><header class="desktop" id="header-desktop">
    <div class="header-wrapper">
        <div class="header-title">
            <a href="/" title="记录从零开始的过程">Cuasloi</a>
        </div>
        <div class="menu">
            <div class="menu-inner"><a class="menu-item" href="/posts/"> 文章 </a><a class="menu-item" href="/tags/"> 标签 </a><a class="menu-item" href="/categories/"> 分类 </a><span class="menu-item delimiter"></span><span class="menu-item search" id="search-desktop">
                        <input type="text" placeholder="搜索文章标题或内容..." id="search-input-desktop">
                        <a href="javascript:void(0);" class="search-button search-toggle" id="search-toggle-desktop" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="javascript:void(0);" class="search-button search-clear" id="search-clear-desktop" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-desktop">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </span><a href="javascript:void(0);" class="menu-item theme-switch" title="切换主题">
                    <i class="fas fa-adjust fa-fw"></i>
                </a>
            </div>
        </div>
    </div>
</header><header class="mobile" id="header-mobile">
    <div class="header-container">
        <div class="header-wrapper">
            <div class="header-title">
                <a href="/" title="记录从零开始的过程">Cuasloi</a>
            </div>
            <div class="menu-toggle" id="menu-toggle-mobile">
                <span></span><span></span><span></span>
            </div>
        </div>
        <div class="menu" id="menu-mobile"><div class="search-wrapper">
                    <div class="search mobile" id="search-mobile">
                        <input type="text" placeholder="搜索文章标题或内容..." id="search-input-mobile">
                        <a href="javascript:void(0);" class="search-button search-toggle" id="search-toggle-mobile" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="javascript:void(0);" class="search-button search-clear" id="search-clear-mobile" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-mobile">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </div>
                    <a href="javascript:void(0);" class="search-cancel" id="search-cancel-mobile">
                        取消
                    </a>
                </div><a class="menu-item" href="/posts/" title="">文章</a><a class="menu-item" href="/tags/" title="">标签</a><a class="menu-item" href="/categories/" title="">分类</a><a href="javascript:void(0);" class="menu-item theme-switch" title="切换主题">
                <i class="fas fa-adjust fa-fw"></i>
            </a></div>
    </div>
</header>
<div class="search-dropdown desktop">
    <div id="search-dropdown-desktop"></div>
</div>
<div class="search-dropdown mobile">
    <div id="search-dropdown-mobile"></div>
</div>
<main class="main">
                <div class="container"><div class="toc" id="toc-auto">
            <h2 class="toc-title">目录</h2>
            <div class="toc-content" id="toc-content-auto"></div>
        </div><article class="page single"><h1 class="single-title animated flipInX">Mqtt入门</h1><div class="post-meta">
            <div class="post-meta-line"><span class="post-author"><a href="/" title="Author" rel=" author" class="author"><i class="fas fa-user-circle fa-fw"></i>Cuasloi</a></span>&nbsp;<span class="post-category">收录于 <a href="/categories/springboot/"><i class="far fa-folder fa-fw"></i>SpringBoot</a></span></div>
            <div class="post-meta-line"><i class="far fa-calendar-alt fa-fw"></i>&nbsp;<time datetime="2021-11-17">2021-11-17</time>&nbsp;<i class="fas fa-pencil-alt fa-fw"></i>&nbsp;约 1296 字&nbsp;
                <i class="far fa-clock fa-fw"></i>&nbsp;预计阅读 3 分钟&nbsp;</div>
        </div><div class="details toc" id="toc-static"  kept="">
                <div class="details-summary toc-title">
                    <span>目录</span>
                    <span><i class="details-icon fas fa-angle-right"></i></span>
                </div>
                <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents">
  <ul>
    <li>
      <ul>
        <li><a href="#导入依赖">导入依赖</a></li>
        <li><a href="#yaml设置mqtt连接参数">yaml设置mqtt连接参数</a></li>
        <li><a href="#编写配置文件">编写配置文件</a></li>
        <li><a href="#编写消息处理类">编写消息处理类</a></li>
        <li><a href="#发布消息网关">发布消息网关</a></li>
        <li><a href="#编写发消息接口">编写发消息接口</a></li>
        <li><a href="#用到的常量配置类">用到的常量配置类</a></li>
        <li><a href="#测试">测试</a></li>
      </ul>
    </li>
  </ul>
</nav></div>
            </div><div class="content" id="content"><p>SpringBoot整合MQTT</p>
<h3 id="导入依赖">导入依赖</h3>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="nt">&lt;dependency&gt;</span>
    <span class="nt">&lt;groupId&gt;</span>org.springframework.boot<span class="nt">&lt;/groupId&gt;</span>
    <span class="nt">&lt;artifactId&gt;</span>spring-boot-configuration-processor<span class="nt">&lt;/artifactId&gt;</span>
<span class="nt">&lt;/dependency&gt;</span>

<span class="nt">&lt;dependency&gt;</span>
    <span class="nt">&lt;groupId&gt;</span>org.springframework.integration<span class="nt">&lt;/groupId&gt;</span>
    <span class="nt">&lt;artifactId&gt;</span>spring-integration-mqtt<span class="nt">&lt;/artifactId&gt;</span>
<span class="nt">&lt;/dependency&gt;</span>

<span class="nt">&lt;dependency&gt;</span>
    <span class="nt">&lt;groupId&gt;</span>org.springframework.boot<span class="nt">&lt;/groupId&gt;</span>
    <span class="nt">&lt;artifactId&gt;</span>spring-boot-starter-web<span class="nt">&lt;/artifactId&gt;</span>
<span class="nt">&lt;/dependency&gt;</span>
</code></pre></td></tr></table>
</div>
</div><h3 id="yaml设置mqtt连接参数">yaml设置mqtt连接参数</h3>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="nt">mqtt</span><span class="p">:</span><span class="w">
</span><span class="w">  </span><span class="nt">username</span><span class="p">:</span><span class="w"> </span><span class="l">admin</span><span class="w">
</span><span class="w">  </span><span class="nt">password</span><span class="p">:</span><span class="w"> </span><span class="l">public</span><span class="w">
</span><span class="w">  </span><span class="nt">url</span><span class="p">:</span><span class="w"> </span><span class="l">tcp://192.168.0.103:1883 </span><span class="w"> </span><span class="c"># 改成自己的服务器地址</span><span class="w">
</span><span class="w">  </span><span class="nt">defaultTopic</span><span class="p">:</span><span class="w"> </span><span class="l">test</span><span class="w">
</span><span class="w">  </span><span class="nt">clientId</span><span class="p">:</span><span class="w"> </span><span class="l">mqttdemo</span><span class="w">
</span></code></pre></td></tr></table>
</div>
</div><h3 id="编写配置文件">编写配置文件</h3>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">  1
</span><span class="lnt">  2
</span><span class="lnt">  3
</span><span class="lnt">  4
</span><span class="lnt">  5
</span><span class="lnt">  6
</span><span class="lnt">  7
</span><span class="lnt">  8
</span><span class="lnt">  9
</span><span class="lnt"> 10
</span><span class="lnt"> 11
</span><span class="lnt"> 12
</span><span class="lnt"> 13
</span><span class="lnt"> 14
</span><span class="lnt"> 15
</span><span class="lnt"> 16
</span><span class="lnt"> 17
</span><span class="lnt"> 18
</span><span class="lnt"> 19
</span><span class="lnt"> 20
</span><span class="lnt"> 21
</span><span class="lnt"> 22
</span><span class="lnt"> 23
</span><span class="lnt"> 24
</span><span class="lnt"> 25
</span><span class="lnt"> 26
</span><span class="lnt"> 27
</span><span class="lnt"> 28
</span><span class="lnt"> 29
</span><span class="lnt"> 30
</span><span class="lnt"> 31
</span><span class="lnt"> 32
</span><span class="lnt"> 33
</span><span class="lnt"> 34
</span><span class="lnt"> 35
</span><span class="lnt"> 36
</span><span class="lnt"> 37
</span><span class="lnt"> 38
</span><span class="lnt"> 39
</span><span class="lnt"> 40
</span><span class="lnt"> 41
</span><span class="lnt"> 42
</span><span class="lnt"> 43
</span><span class="lnt"> 44
</span><span class="lnt"> 45
</span><span class="lnt"> 46
</span><span class="lnt"> 47
</span><span class="lnt"> 48
</span><span class="lnt"> 49
</span><span class="lnt"> 50
</span><span class="lnt"> 51
</span><span class="lnt"> 52
</span><span class="lnt"> 53
</span><span class="lnt"> 54
</span><span class="lnt"> 55
</span><span class="lnt"> 56
</span><span class="lnt"> 57
</span><span class="lnt"> 58
</span><span class="lnt"> 59
</span><span class="lnt"> 60
</span><span class="lnt"> 61
</span><span class="lnt"> 62
</span><span class="lnt"> 63
</span><span class="lnt"> 64
</span><span class="lnt"> 65
</span><span class="lnt"> 66
</span><span class="lnt"> 67
</span><span class="lnt"> 68
</span><span class="lnt"> 69
</span><span class="lnt"> 70
</span><span class="lnt"> 71
</span><span class="lnt"> 72
</span><span class="lnt"> 73
</span><span class="lnt"> 74
</span><span class="lnt"> 75
</span><span class="lnt"> 76
</span><span class="lnt"> 77
</span><span class="lnt"> 78
</span><span class="lnt"> 79
</span><span class="lnt"> 80
</span><span class="lnt"> 81
</span><span class="lnt"> 82
</span><span class="lnt"> 83
</span><span class="lnt"> 84
</span><span class="lnt"> 85
</span><span class="lnt"> 86
</span><span class="lnt"> 87
</span><span class="lnt"> 88
</span><span class="lnt"> 89
</span><span class="lnt"> 90
</span><span class="lnt"> 91
</span><span class="lnt"> 92
</span><span class="lnt"> 93
</span><span class="lnt"> 94
</span><span class="lnt"> 95
</span><span class="lnt"> 96
</span><span class="lnt"> 97
</span><span class="lnt"> 98
</span><span class="lnt"> 99
</span><span class="lnt">100
</span><span class="lnt">101
</span><span class="lnt">102
</span><span class="lnt">103
</span><span class="lnt">104
</span><span class="lnt">105
</span><span class="lnt">106
</span><span class="lnt">107
</span><span class="lnt">108
</span><span class="lnt">109
</span><span class="lnt">110
</span><span class="lnt">111
</span><span class="lnt">112
</span><span class="lnt">113
</span><span class="lnt">114
</span><span class="lnt">115
</span><span class="lnt">116
</span><span class="lnt">117
</span><span class="lnt">118
</span><span class="lnt">119
</span><span class="lnt">120
</span><span class="lnt">121
</span><span class="lnt">122
</span><span class="lnt">123
</span><span class="lnt">124
</span><span class="lnt">125
</span><span class="lnt">126
</span><span class="lnt">127
</span><span class="lnt">128
</span><span class="lnt">129
</span><span class="lnt">130
</span><span class="lnt">131
</span><span class="lnt">132
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kn">import</span> <span class="nn">lombok.Data</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">lombok.extern.log4j.Log4j2</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.eclipse.paho.client.mqttv3.MqttConnectOptions</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.springframework.beans.factory.annotation.Autowired</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.springframework.beans.factory.annotation.Qualifier</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.springframework.boot.context.properties.ConfigurationProperties</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.springframework.context.annotation.Bean</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.springframework.context.annotation.Configuration</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.springframework.integration.annotation.ServiceActivator</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.springframework.integration.channel.DirectChannel</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.springframework.integration.core.MessageProducer</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.springframework.integration.mqtt.core.MqttPahoClientFactory</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.springframework.integration.mqtt.support.DefaultPahoMessageConverter</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.springframework.messaging.MessageChannel</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.springframework.messaging.MessageHandler</span><span class="o">;</span>


<span class="nd">@Configuration</span>
<span class="nd">@ConfigurationProperties</span><span class="o">(</span><span class="n">prefix</span> <span class="o">=</span> <span class="s">&#34;mqtt&#34;</span><span class="o">)</span>
<span class="nd">@Data</span>
<span class="nd">@Log4j2</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">MqttConfig</span> <span class="o">{</span>


    <span class="kd">private</span> <span class="n">String</span> <span class="n">username</span><span class="o">;</span>

    <span class="kd">private</span> <span class="n">String</span> <span class="n">password</span><span class="o">;</span>

    <span class="kd">private</span> <span class="n">String</span> <span class="n">url</span><span class="o">;</span>

    <span class="kd">private</span> <span class="n">String</span> <span class="n">clientId</span><span class="o">;</span>

    <span class="kd">private</span> <span class="n">String</span> <span class="n">defaultTopic</span><span class="o">;</span>

    <span class="c1">// 注入消息处理类
</span><span class="c1"></span>    <span class="nd">@Autowired</span>
    <span class="nd">@Qualifier</span><span class="o">(</span><span class="s">&#34;input&#34;</span><span class="o">)</span>
    <span class="kd">private</span> <span class="n">MessageHandler</span> <span class="n">messageHandler</span><span class="o">;</span>

    <span class="cm">/**
</span><span class="cm">     * Mqtt 连接配置
</span><span class="cm">     */</span>
    <span class="nd">@Bean</span>
    <span class="kd">public</span> <span class="n">MqttConnectOptions</span> <span class="nf">mqttConnectOptions</span><span class="o">()</span> <span class="o">{</span>
        <span class="n">MqttConnectOptions</span> <span class="n">options</span> <span class="o">=</span> <span class="k">new</span> <span class="n">MqttConnectOptions</span><span class="o">();</span>

        <span class="c1">// 设置连接的用户名
</span><span class="c1"></span>        <span class="n">options</span><span class="o">.</span><span class="na">setUserName</span><span class="o">(</span><span class="n">username</span><span class="o">);</span>

        <span class="c1">// 设置连接的密码
</span><span class="c1"></span>        <span class="n">options</span><span class="o">.</span><span class="na">setPassword</span><span class="o">(</span><span class="n">password</span><span class="o">.</span><span class="na">toCharArray</span><span class="o">());</span>

        <span class="c1">// 设置连接的地址
</span><span class="c1"></span>        <span class="n">options</span><span class="o">.</span><span class="na">setServerURIs</span><span class="o">(</span><span class="k">new</span> <span class="n">String</span><span class="o">[]{</span><span class="n">url</span><span class="o">});</span>

        <span class="c1">// 设置超时时间 单位为秒
</span><span class="c1"></span>        <span class="n">options</span><span class="o">.</span><span class="na">setConnectionTimeout</span><span class="o">(</span><span class="n">10</span><span class="o">);</span>

        <span class="c1">// 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送心跳判断客户端是否在线
</span><span class="c1"></span>        <span class="c1">// 但这个方法并没有重连的机制
</span><span class="c1"></span>        <span class="n">options</span><span class="o">.</span><span class="na">setKeepAliveInterval</span><span class="o">(</span><span class="n">20</span><span class="o">);</span>

        <span class="c1">// 设置 &#34;遗嘱&#34; 消息的话题，若客户端与服务器之间的连接意外中断，服务器将发布客户端的&#34;遗嘱&#34;消息。
</span><span class="c1"></span>        <span class="n">options</span><span class="o">.</span><span class="na">setWill</span><span class="o">(</span><span class="s">&#34;willTopic&#34;</span><span class="o">,</span> <span class="n">WILL_DATA</span><span class="o">,</span> <span class="n">2</span><span class="o">,</span> <span class="kc">false</span><span class="o">);</span>
        <span class="k">return</span> <span class="n">options</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="cm">/**
</span><span class="cm">     * Mqtt 客户端工厂
</span><span class="cm">     */</span>
    <span class="nd">@Bean</span>
    <span class="kd">public</span> <span class="n">MqttPahoClientFactory</span> <span class="nf">mqttClientFactory</span><span class="o">()</span> <span class="o">{</span>
        <span class="n">DefaultMqttPahoClientFactory</span> <span class="n">factory</span> <span class="o">=</span> <span class="k">new</span> <span class="n">DefaultMqttPahoClientFactory</span><span class="o">();</span>
        <span class="n">factory</span><span class="o">.</span><span class="na">setConnectionOptions</span><span class="o">(</span><span class="n">mqttConnectOptions</span><span class="o">());</span>
        <span class="k">return</span> <span class="n">factory</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="cm">/**
</span><span class="cm">     * 创建一个名为CHANNEL_OUT消息管道
</span><span class="cm">     */</span>
    <span class="nd">@Bean</span><span class="o">(</span><span class="n">name</span> <span class="o">=</span> <span class="n">CHANNEL_OUT</span><span class="o">)</span>
    <span class="kd">public</span> <span class="n">MessageChannel</span> <span class="nf">mqttOutboundChannel</span><span class="o">()</span> <span class="o">{</span>
        <span class="k">return</span> <span class="k">new</span> <span class="n">DirectChannel</span><span class="o">();</span>
    <span class="o">}</span>

    <span class="cm">/**
</span><span class="cm">     * 消息处理， @ServiceActivator表明此方法会处理CHANNEL_OUT通道的消息
</span><span class="cm">     */</span>
    <span class="nd">@Bean</span>
    <span class="nd">@ServiceActivator</span><span class="o">(</span><span class="n">inputChannel</span> <span class="o">=</span> <span class="n">CHANNEL_OUT</span><span class="o">)</span>
    <span class="kd">public</span> <span class="n">MessageHandler</span> <span class="nf">mqttOutbound</span><span class="o">()</span> <span class="o">{</span>
        <span class="n">MqttPahoMessageHandler</span> <span class="n">messageHandler</span> <span class="o">=</span> <span class="k">new</span> <span class="n">MqttPahoMessageHandler</span><span class="o">(</span><span class="n">clientId</span><span class="o">,</span> <span class="n">mqttClientFactory</span><span class="o">());</span>
        <span class="n">messageHandler</span><span class="o">.</span><span class="na">setAsync</span><span class="o">(</span><span class="kc">true</span><span class="o">);</span>
        <span class="n">messageHandler</span><span class="o">.</span><span class="na">setDefaultTopic</span><span class="o">(</span><span class="n">defaultTopic</span><span class="o">);</span>
        <span class="k">return</span> <span class="n">messageHandler</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="cm">/**
</span><span class="cm">     * 创建一个名为CHANNEL_IN消息管道， @MessagingGateway发送消息会使用这个通道
</span><span class="cm">     */</span>
    <span class="nd">@Bean</span><span class="o">(</span><span class="n">name</span> <span class="o">=</span> <span class="n">CHANNEL_IN</span><span class="o">)</span>
    <span class="kd">public</span> <span class="n">MessageChannel</span> <span class="nf">mqttInputChannel</span><span class="o">()</span> <span class="o">{</span>
        <span class="k">return</span> <span class="k">new</span> <span class="n">DirectChannel</span><span class="o">();</span>
    <span class="o">}</span>

    <span class="cm">/**
</span><span class="cm">     * 配置订阅消息， 订阅的主题，及消息通道
</span><span class="cm">     */</span>
    <span class="nd">@Bean</span>
    <span class="kd">public</span> <span class="n">MessageProducer</span> <span class="nf">inbound</span><span class="o">()</span> <span class="o">{</span>
        <span class="n">MqttPahoMessageDrivenChannelAdapter</span> <span class="n">adapter</span> <span class="o">=</span> <span class="k">new</span> <span class="n">MqttPahoMessageDrivenChannelAdapter</span><span class="o">(</span>
                <span class="n">clientId</span> <span class="o">+</span> <span class="s">&#34;_inbound&#34;</span><span class="o">,</span> <span class="n">mqttClientFactory</span><span class="o">(),</span> <span class="n">defaultTopic</span><span class="o">);</span>
        <span class="n">adapter</span><span class="o">.</span><span class="na">setCompletionTimeout</span><span class="o">(</span><span class="n">3000</span><span class="o">);</span>
        <span class="n">adapter</span><span class="o">.</span><span class="na">setConverter</span><span class="o">(</span><span class="k">new</span> <span class="n">DefaultPahoMessageConverter</span><span class="o">());</span>
        <span class="n">adapter</span><span class="o">.</span><span class="na">setQos</span><span class="o">(</span><span class="n">1</span><span class="o">);</span>
        <span class="n">adapter</span><span class="o">.</span><span class="na">setOutputChannel</span><span class="o">(</span><span class="n">mqttInputChannel</span><span class="o">());</span>
        <span class="k">return</span> <span class="n">adapter</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="cm">/**
</span><span class="cm">     * 订阅消息处理， @ServiceActivator表明此方法会处理CHANNEL_IN通道的消息
</span><span class="cm">     */</span>
    <span class="nd">@Bean</span>
    <span class="nd">@ServiceActivator</span><span class="o">(</span><span class="n">inputChannel</span> <span class="o">=</span> <span class="n">CHANNEL_IN</span><span class="o">)</span>
    <span class="kd">public</span> <span class="n">MessageHandler</span> <span class="nf">handler</span><span class="o">()</span> <span class="o">{</span>
        <span class="k">return</span> <span class="n">messageHandler</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span>

</code></pre></td></tr></table>
</div>
</div><h3 id="编写消息处理类">编写消息处理类</h3>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kn">import</span> <span class="nn">lombok.extern.log4j.Log4j2</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.springframework.beans.factory.annotation.Qualifier</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.springframework.messaging.Message</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.springframework.messaging.MessageHandler</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.springframework.messaging.MessagingException</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.springframework.stereotype.Component</span><span class="o">;</span>

<span class="kn">import</span> <span class="nn">java.util.Objects</span><span class="o">;</span>

<span class="nd">@Component</span>
<span class="nd">@Qualifier</span><span class="o">(</span><span class="s">&#34;input&#34;</span><span class="o">)</span>
<span class="nd">@Log4j2</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">MqttMessageHandler</span> <span class="kd">implements</span> <span class="n">MessageHandler</span> <span class="o">{</span>

    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">handleMessage</span><span class="o">(</span><span class="n">Message</span><span class="o">&lt;?&gt;</span> <span class="n">message</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">MessagingException</span> <span class="o">{</span>
        <span class="n">String</span> <span class="n">topic</span> <span class="o">=</span> <span class="n">Objects</span><span class="o">.</span><span class="na">requireNonNull</span><span class="o">(</span><span class="n">message</span><span class="o">.</span><span class="na">getHeaders</span><span class="o">().</span><span class="na">get</span><span class="o">(</span><span class="s">&#34;mqtt_receivedTopic&#34;</span><span class="o">)).</span><span class="na">toString</span><span class="o">();</span>
        <span class="n">log</span><span class="o">.</span><span class="na">info</span><span class="o">(</span><span class="s">&#34;topic: {}&#34;</span><span class="o">,</span> <span class="n">topic</span><span class="o">);</span>
        <span class="n">log</span><span class="o">.</span><span class="na">info</span><span class="o">(</span><span class="s">&#34;payload: {}&#34;</span><span class="o">,</span> <span class="n">message</span><span class="o">.</span><span class="na">getPayload</span><span class="o">().</span><span class="na">toString</span><span class="o">());</span>
    <span class="o">}</span>

<span class="o">}</span>
</code></pre></td></tr></table>
</div>
</div><h3 id="发布消息网关">发布消息网关</h3>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span><span class="lnt">33
</span><span class="lnt">34
</span><span class="lnt">35
</span><span class="lnt">36
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kn">import</span> <span class="nn">org.springframework.integration.annotation.MessagingGateway</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.springframework.integration.mqtt.support.MqttHeaders</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.springframework.messaging.handler.annotation.Header</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.springframework.stereotype.Component</span><span class="o">;</span>

<span class="nd">@Component</span>
<span class="nd">@MessagingGateway</span><span class="o">(</span><span class="n">defaultRequestChannel</span> <span class="o">=</span> <span class="n">MqttConstants</span><span class="o">.</span><span class="na">CHANNEL_OUT</span><span class="o">)</span>
<span class="kd">public</span> <span class="kd">interface</span> <span class="nc">MqttGateway</span> <span class="o">{</span>

    <span class="cm">/**
</span><span class="cm">     * 发送信息到 MQTT 服务器
</span><span class="cm">     *
</span><span class="cm">     * @param data 发送的文本
</span><span class="cm">     */</span>
    <span class="kt">void</span> <span class="nf">sendToMqtt</span><span class="o">(</span><span class="n">String</span> <span class="n">data</span><span class="o">);</span>

    <span class="cm">/**
</span><span class="cm">     * 发送信息到 MQTT 服务器
</span><span class="cm">     *
</span><span class="cm">     * @param topic 主题
</span><span class="cm">     * @param payload 消息主体
</span><span class="cm">     */</span>
    <span class="kt">void</span> <span class="nf">sendToMqtt</span><span class="o">(</span><span class="nd">@Header</span><span class="o">(</span><span class="n">MqttHeaders</span><span class="o">.</span><span class="na">TOPIC</span><span class="o">)</span> <span class="n">String</span> <span class="n">topic</span><span class="o">,</span> <span class="n">String</span> <span class="n">payload</span><span class="o">);</span>

    <span class="cm">/**
</span><span class="cm">     * 发送信息到 MQTT 服务器
</span><span class="cm">     *
</span><span class="cm">     * @param topic 主题
</span><span class="cm">     * @param qos 对消息处理的几种机制。
</span><span class="cm">     * 0 表示的是订阅者没收到消息不会再次发送，消息会丢失。
</span><span class="cm">     * 1 表示的是会尝试重试，一直到接收到消息，但这种情况可能导致订阅者收到多次重复消息。
</span><span class="cm">     * 2 多了一次去重的动作，确保订阅者收到的消息有一次。
</span><span class="cm">     * @param payload 消息主体
</span><span class="cm">     */</span>
    <span class="kt">void</span> <span class="nf">sendToMqtt</span><span class="o">(</span><span class="nd">@Header</span><span class="o">(</span><span class="n">MqttHeaders</span><span class="o">.</span><span class="na">TOPIC</span><span class="o">)</span> <span class="n">String</span> <span class="n">topic</span><span class="o">,</span> <span class="nd">@Header</span><span class="o">(</span><span class="n">MqttHeaders</span><span class="o">.</span><span class="na">QOS</span><span class="o">)</span> <span class="kt">int</span> <span class="n">qos</span><span class="o">,</span> <span class="n">String</span> <span class="n">payload</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></td></tr></table>
</div>
</div><h3 id="编写发消息接口">编写发消息接口</h3>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kn">import</span> <span class="nn">lombok.extern.log4j.Log4j2</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.cuasloi.mqtt.config.MqttGateway</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.springframework.beans.factory.annotation.Autowired</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.springframework.web.bind.annotation.GetMapping</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.springframework.web.bind.annotation.RestController</span><span class="o">;</span>


<span class="nd">@RestController</span>
<span class="nd">@Log4j2</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">SendController</span> <span class="o">{</span>

    <span class="nd">@Autowired</span>
    <span class="kd">private</span> <span class="n">MqttGateway</span> <span class="n">mqttSend</span><span class="o">;</span>

    <span class="cm">/**
</span><span class="cm">     * 发送自定义消息内容（使用默认主题）
</span><span class="cm">     * @param content 消息内容
</span><span class="cm">     */</span>
    <span class="nd">@GetMapping</span><span class="o">(</span><span class="n">value</span> <span class="o">=</span> <span class="s">&#34;/send&#34;</span><span class="o">)</span>
    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">test1</span><span class="o">(</span><span class="n">String</span> <span class="n">content</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">log</span><span class="o">.</span><span class="na">info</span><span class="o">(</span><span class="s">&#34;-----&gt;{}&#34;</span><span class="o">,</span> <span class="s">&#34;mqtt 消息发布，使用默认主题发布:&#34;</span> <span class="o">+</span> <span class="n">content</span><span class="o">);</span>
        <span class="n">mqttSend</span><span class="o">.</span><span class="na">sendToMqtt</span><span class="o">(</span><span class="n">content</span><span class="o">);</span>
    <span class="o">}</span>

<span class="o">}</span>
</code></pre></td></tr></table>
</div>
</div><h3 id="用到的常量配置类">用到的常量配置类</h3>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="kn">import</span> <span class="nn">java.nio.charset.StandardCharsets</span><span class="o">;</span>

<span class="kd">public</span> <span class="kd">interface</span> <span class="nc">MqttConstants</span> <span class="o">{</span>

    <span class="n">String</span> <span class="n">CHANNEL_OUT</span> <span class="o">=</span> <span class="s">&#34;mqttOutboundChannel&#34;</span><span class="o">;</span>
    <span class="n">String</span> <span class="n">CHANNEL_IN</span> <span class="o">=</span> <span class="s">&#34;mqttInputChannel&#34;</span><span class="o">;</span>

    <span class="kt">byte</span><span class="o">[]</span> <span class="n">WILL_DATA</span> <span class="o">=</span> <span class="s">&#34;offLine&#34;</span><span class="o">.</span><span class="na">getBytes</span><span class="o">(</span><span class="n">StandardCharsets</span><span class="o">.</span><span class="na">UTF_8</span><span class="o">);</span>

<span class="o">}</span>
</code></pre></td></tr></table>
</div>
</div><h3 id="测试">测试</h3>
<p>本地测试 <a href="http://localhost:8080/send?content=HellowMqtt" target="_blank" rel="noopener noreffer">localhost:8080</a></p></div><div class="post-footer" id="post-footer">
    <div class="post-info">
        <div class="post-info-line">
            <div class="post-info-mod">
                <span>更新于 2021-11-17</span>
            </div>
            <div class="post-info-license"></div>
        </div>
        <div class="post-info-line">
            <div class="post-info-md"></div>
            <div class="post-info-share">
                <span><a href="javascript:void(0);" title="分享到 微博" data-sharer="weibo" data-url="http://example.org/mqtt%E5%85%A5%E9%97%A8/" data-title="Mqtt入门"><i class="fab fa-weibo fa-fw"></i></a></span>
            </div>
        </div>
    </div>

    <div class="post-info-more">
        <section class="post-tags"><i class="fas fa-tags fa-fw"></i>&nbsp;<a href="/tags/mqtt/">mqtt</a>,&nbsp;<a href="/tags/springboot/">SpringBoot</a></section>
        <section>
            <span><a href="javascript:void(0);" onclick="window.history.back();">返回</a></span>&nbsp;|&nbsp;<span><a href="/">主页</a></span>
        </section>
    </div>

    <div class="post-nav"><a href="/docker%E5%AE%89%E8%A3%85emqx/" class="prev" rel="prev" title="Docker安装emqx"><i class="fas fa-angle-left fa-fw"></i>Docker安装emqx</a>
            <a href="/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E4%BB%8B%E7%BB%8D/" class="next" rel="next" title="设计模式介绍">设计模式介绍<i class="fas fa-angle-right fa-fw"></i></a></div>
</div>
<div id="comments"></div></article></div>
            </main><footer class="footer">
        <div class="footer-container"><div class="footer-line">由 <a href="https://gohugo.io/" target="_blank" rel="noopener noreffer" title="Hugo 0.89.0">Hugo</a> 强力驱动 | 主题 - <a href="https://github.com/dillonzq/LoveIt" target="_blank" rel="noopener noreffer" title="LoveIt 0.2.10"><i class="far fa-kiss-wink-heart fa-fw"></i> LoveIt</a>
                </div><div class="footer-line"><i class="far fa-copyright fa-fw"></i><span itemprop="copyrightYear">2021</span><span class="author" itemprop="copyrightHolder">&nbsp;<a href="/" target="_blank">Cuasloi</a></span>&nbsp;|&nbsp;<span class="license"><a rel="license external nofollow noopener noreffer" href="https://creativecommons.org/licenses/by-nc/4.0/" target="_blank">CC BY-NC 4.0</a></span></div>
        </div>
    </footer></div>

        <div id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="回到顶部">
                <i class="fas fa-arrow-up fa-fw"></i>
            </a><a href="#" id="view-comments" class="fixed-button" title="查看评论">
                <i class="fas fa-comment fa-fw"></i>
            </a>
        </div><script type="text/javascript" src="/lib/smooth-scroll/smooth-scroll.min.js"></script><script type="text/javascript" src="/lib/autocomplete/autocomplete.min.js"></script><script type="text/javascript" src="/lib/lunr/lunr.min.js"></script><script type="text/javascript" src="/lib/lunr/lunr.stemmer.support.min.js"></script><script type="text/javascript" src="/lib/lunr/lunr.zh.min.js"></script><script type="text/javascript" src="/lib/lazysizes/lazysizes.min.js"></script><script type="text/javascript" src="/lib/clipboard/clipboard.min.js"></script><script type="text/javascript" src="/lib/sharer/sharer.min.js"></script><script type="text/javascript">window.config={"code":{"copyTitle":"复制到剪贴板","maxShownLines":10},"comment":{},"search":{"highlightTag":"em","lunrIndexURL":"/index.json","lunrLanguageCode":"zh","lunrSegmentitURL":"/lib/lunr/lunr.segmentit.js","maxResultLength":10,"noResultsFound":"没有找到结果","snippetLength":50,"type":"lunr"}};</script><script type="text/javascript" src="/js/theme.min.js"></script></body>
</html>
